# -*- coding: utf8 -*-

from project.sqlite3_db.table import Table

class TableOption( Table ):

    _table_name = "option"

    def create( self ):
        c = self.getCursor()

        # Create table
        c.execute(
            "CREATE TABLE IF NOT EXISTS option ("+
            "id INTEGER PRIMARY KEY, "+
            "name TEXT, "+
            "value TEXT)"
        )
        c.close()
        return


    def save_option( self, name, value ):
        cur = self.getCursor()

        cur.execute("SELECT * FROM option WHERE name=:name",
                {"name": name}
        )
        item = cur.fetchone()

        if not item:
            cur.execute("INSERT INTO option(name, value) VALUES (?, ?)", (name, value))
            item = cur.lastrowid
        else:
            cur.execute("UPDATE option SET value=:value WHERE name=:name",
                    {"name":name, "value":value}
            )
            item = item["id"]
        cur.close()
        self.getConnection().commit()
        return item

    def get_option( self, name ):
        cur = self.getCursor()
        cur.execute("SELECT value FROM option WHERE name=:name",
                {"name": name}
        )
        item = cur.fetchone()
        if item:
            item = item["value"]
        cur.close()
        return item


    def get_options( self ):
        cur = self.getCursor()
        cur.execute("SELECT * FROM option")
        items = cur.fetchall()
        cur.close()
        opts = {}
        for item in items:
            opts[ item["name"] ] = item["value"]
        return opts

    pass
